package com.jzoom.zoom.admin.controllers;

import com.jzoom.zoom.admin.annotations.IgnoreOutput;
import com.jzoom.zoom.admin.models.ShellService;
import com.jzoom.zoom.common.annotations.Inject;
import com.jzoom.zoom.web.annotations.Controller;
import com.jzoom.zoom.web.annotations.JsonResponse;
import com.jzoom.zoom.web.exception.StatusException;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

@Controller(key="shell")
public class ShellController implements AdminController {

    @Inject
    private ShellService shellService;

    /**
     * 获取或者创建session
     * @param id
     * @return
     */
    @JsonResponse
    public synchronized String connect(String id) {
        ShellService.ShellSession shellSession =null;
        if(id!=null){
            shellSession = shellService.getSession(id);
        }
        if(shellSession == null){
            try {
                shellSession = shellService.openSession();
            } catch (IOException e) {
               throw new StatusException.ApiError("创建session失败，请稍后重试");
            }
        }
        return shellSession.getSessionId();

    }

    /**
     * 获取所有输出
     */
    @IgnoreOutput
    @JsonResponse
    public List<String> outputs(String id){
        ShellService.ShellSession shellSession = shellService.getSession(id);
        if(shellSession==null){
            throw new StatusException.ApiError("Session不存在");
        }
        return shellSession.getOutputs();
    }



    @JsonResponse
    public void close(String id){
        ShellService.ShellSession shellSession = shellService.getSession(id);
        if(shellSession==null){
            return;
        }
        shellSession.destroy();
    }


    @JsonResponse
    public List<String> send(String id, String command) {
        if(id==null || command == null){
            throw new StatusException.BadRequest();
        }
        ShellService.ShellSession shellSession = shellService.getSession(id);
        if(shellSession==null){
            throw new StatusException.ApiError("Session不存在");
        }
        try {
            shellSession.send(command);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
                return Collections.emptyList();
            }
            return shellSession.getOutputs();
        } catch (IOException e) {
            throw new StatusException.ApiError("发生异常");
        }
    }

}
